<template>
  <div class="OrderDetails">
    <div class="demo-nav">
      <div class="demo-nav__title">订单详情</div>
      <svg viewBox="0 0 1000 1000" class="demo-nav__back" @click="toBack">
        <path fill-rule="evenodd" fill="#969799" d="M296.114 508.035c-3.22-13.597.473-28.499 11.079-39.105l333.912-333.912c16.271-16.272 42.653-16.272 58.925 0s16.272 42.654 0 58.926L395.504 498.47l304.574 304.574c16.272 16.272 16.272 42.654 0 58.926s-42.654 16.272-58.926 0L307.241 528.058a41.472 41.472 0 0 1-11.127-20.023z"></path>
      </svg>
    </div>
    <div class="OrderDetails-demo">
      <van-tabs v-model="activeName">
        <van-tab title="门店配送" name="a" align="left">
          <van-cell is-link size="large" center @click="toAddress">
            <!-- 使用 title 插槽来自定义标题 -->
            <template #title>
              <van-tag type="danger">{{customerAddress != null ? '默认':''}}</van-tag>
              <span class="custom-title" style="font-size: 0.7rem;color: black">{{customerAddress != null ? customerAddress.province : "暂无配送地址"}}
                {{customerAddress != null ? customerAddress.city : ""}}  {{customerAddress != null ? customerAddress.county : ""}}</span>
              <br>
              <P style="font-size: 0.7rem">{{customerAddress != null ? customerAddress.addressDetail : ""}}</P>
              <P style="font-size: 0.7rem">{{customerAddress != null ? customerAddress.name : ""}}    {{customerAddress != null ? customerAddress.tel :""}}</P>
            </template>
          </van-cell>
          <van-card
            :num="this.selectedNum"
            :tag="this.product.shopsName"
            :price="this.sku.groupPrice"
            :desc="this.sku.labelName +' / '+ this.product.descript"
            :title="this.product.productName"
            :thumb="this.sku.productPicInfo.picUrl">
          </van-card>
          <van-checkbox-group v-model="result">
            <van-cell-group>
              <van-cell
                clickable
                title="开发票">
                <template #right-icon>
                  <van-checkbox name="item" ref="checkboxes" @click="toggle()" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-checkbox-group>
          <van-cell-group>
            <van-field v-model="orderPaper" v-show="orderPaperShow" label="抬头票" placeholder="请输入抬头票" />
          </van-cell-group>
          <!-- 优惠券单元格 -->
          <van-coupon-cell
            :coupons="coupons"
            :chosen-coupon="chosenCoupon"
            @click="showList = true"
          />
          <!-- 优惠券列表 -->
          <van-popup
            v-model="showList"
            round
            position="bottom"
            style="height: 90%; padding-top: 4px;"
          >
            <van-coupon-list
              :coupons="coupons"
              :chosen-coupon="chosenCoupon"
              :disabled-coupons="disabledCoupons"
              :show-exchange-bar="false"
              @change="onChange"
              @exchange="onExchange"
            />
          </van-popup>
          <van-cell title="商品金额" :value="'￥'+this.sku.groupPrice"></van-cell>
          <van-cell title="运费" :value=" this.sku.labelFreight == null ? 0 :'+ ￥' +this.sku.labelFreight"></van-cell>
          <van-submit-bar :price="this.totalPrice*100" button-text="提交订单" @submit="onSubmit1" />
        </van-tab>

        <van-tab title="到店自提" name="b" align="left">
          <van-cell :value="this.product.address" title="自提点" />
          <!-- 输入任意文本 -->
          <van-field v-model="username" label="姓名" placeholder="请填写取货人姓名"/>
          <!-- 输入手机号，调起手机号键盘 -->
          <van-field v-model="phone" type="tel" label="手机" placeholder="请填写取货人手机号"/>
          <van-card
            :num="this.selectedNum"
            :tag="this.product.shopsName"
            :price="this.sku.groupPrice"
            :desc="this.sku.labelName +' / '+ this.product.descript"
            :title="this.product.productName"
            :thumb="this.sku.productPicInfo.picUrl"
          />
          <van-checkbox-group v-model="result2">
            <van-cell-group>
              <van-cell
                clickable
                title="开发票">
                <template #right-icon>
                  <van-checkbox name="item" ref="checkboxes" @click="toggle2()"/>
                </template>
              </van-cell>
            </van-cell-group>
          </van-checkbox-group>
          <van-cell-group>
            <van-field v-model="orderPaper2" v-show="orderPaperShow2" label="抬头票" placeholder="请输入抬头票" />
          </van-cell-group>
          <!-- 优惠券单元格 -->
          <van-coupon-cell
            :coupons="coupons"
            :chosen-coupon="chosenCoupon"
            @click="showList = true"
          />
          <!-- 优惠券列表 -->
          <van-popup
            v-model="showList"
            round
            position="bottom"
            style="height: 90%; padding-top: 4px;"
          >
            <van-coupon-list
              :coupons="coupons"
              :chosen-coupon="chosenCoupon"
              :disabled-coupons="disabledCoupons"
              :show-exchange-bar="false"
              @change="onChange"
              @exchange="onExchange"
            />
          </van-popup>
          <van-cell title="商品金额" :value="'￥'+this.sku.groupPrice"></van-cell>
          <van-submit-bar :price="this.totalPriceb*100" button-text="提交订单" @submit="onSubmit2" />
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script>
  import { zhifu,insertOrderMaster,insertOrderDetail } from "@/api/commodity/alipay";
  import { selectProductById,selectProductLableByLableId } from '@/api/commodity/shop_product.js'
  import { selectCustomerAddrByCustomerId,selectCustomerCouponList } from '@/api/customer/customer.js'
  // 可用优惠券列表
  let coupon;
  // 不可用优惠券列表
  let noCoupon;
  export default {
    name: "Alone",
    data(){
      return{
        // 规格
        sku :{},
        // 商品
        product:{},
        activeName: 'a',
        username:"",
        phone:"",
        result : [],
        result2: [],
        numprice: {},
        showList:false,
        chosenCoupon: -1,
        // 可用优惠券列表
        coupons: coupon,
        // 不可用优惠券列表
        disabledCoupons: noCoupon,
        // 购买数量
        selectedNum: null,
        // 优惠价格
        couponsPrice: null,
        // 门店配送总价格
        totalPrice:null,
        // 到店自提总价格
        totalPriceb: null,
        // 收货地址
        customerAddress: {},
        addShow1:null,
        addShow2:null,
        orderPaper:"",
        orderPaperShow: false,
        orderPaper2:"",
        orderPaperShow2: false,
        // 店铺ID
        supplierId: Number,
        supplierIdOnel:Number,
        // 订单表门店配送表单
        formMaster:{},
        // 订单详情表表单
        formDetail:{},
        // 订单表到店自提表单
        formMasterB:{},
        // 优惠券ID
        availableId:null,

        productId:null,

      }
    },
    //页面加载前渲染
    created() {
      let productId = parseInt(this.$route.query.productId);
      let skuId = parseInt(this.$route.query.skuId);
      let selectedNum = parseInt(this.$route.query.selectedNum);
      let supplierId = parseInt(this.$route.query.supplierId);
      this.supplierIdOnel = supplierId;
      this.selectedNum = selectedNum;
      this.productId = productId;
      this.formDetail.productCnt = selectedNum;
      this.getProductById(productId);
      this.getProductLableByLableId(skuId);
      this.getCustomerAddrByCustomerId();
      // 清空可用优惠券列表
      coupon = [];
      // 清空不可用优惠券列表
      noCoupon = [];
    },
    methods:{
      //返回上一层
      toBack(){
        this.$router.go(-1);
      },
      // 查询商品信息
      getProductById(productId){
        selectProductById(productId).then((res) => {
          console.log("商品信息:"+JSON.stringify(res.data));
        this.formDetail.productId = res.data.data.productId;
        this.formDetail.productName = res.data.data.productName;
        this.product = res.data.data;
        console.log(res.data.data)
        this.supplierId = res.data.data.supplierId;
        this.getCustomerCouponList(res.data.data.supplierId);
      });
      },
      // 查询商品规格信息
      getProductLableByLableId(productLableId){
        selectProductLableByLableId(productLableId).then((res) =>{
          this.formMaster.shippingMoney = res.data.data.labelFreight;
          this.formDetail.labelId = res.data.data.labelId;
          console.log("商品规1111格:"+JSON.stringify(res.data.data.productPicInfo.picUrl))
          this.groupPrice = res.data.data.groupPrice;
          this.sku = res.data.data;
          this.getTotalPrice(this.chosenCoupon);
          this.getTotalPriceb(this.chosenCoupon);
       })
      },
      // 查询默认的地址信息
      getCustomerAddrByCustomerId(){
        selectCustomerAddrByCustomerId().then((res) =>{
          if(res.data.code == 200){
          console.log("收货地址:"+JSON.stringify(res.data))
          this.formMaster.customerId = res.data.data.customerId;
          this.formMasterB.customerId = res.data.data.customerId;
          this.formMaster.customerPhone = res.data.data.tel;
          this.formMaster.shippingUser = res.data.data.name;
          this.formMaster.province = res.data.data.province;
          this.formMasterB.province = res.data.data.province;
          this.formMaster.city = res.data.data.city;
          this.formMasterB.city = res.data.data.city;
          this.formMaster.district = res.data.data.county;
          this.formMasterB.district = res.data.data.county;
          this.formMaster.address = res.data.data.addressDetail;
          this.formMasterB.address = res.data.data.addressDetail;
          this.customerAddress = res.data.data;
          this.addShow1 = false;
          this.addShow2 = true;
        }else{
          this.addShow1 = true;
          this.addShow2 = false;
        }
      })
      },
      // 查询用户可用优惠券
      getCustomerCouponList(supplierId){
        selectCustomerCouponList(supplierId).then((res) =>{
          for (let i = 0; i < res.data.data.length; i++){
          console.log("res.data.data[i].couponPriceMost:"+res.data.data[i].couponPriceMost)
          if(parseFloat(this.totalPrice) >= parseFloat(res.data.data[i].couponPriceMost)){
            coupon.push({ "available": res.data.data[i].couponId,"condition":"满"+res.data.data[i].couponPriceMost +"减"+res.data.data[i].couponPrice,
              "reason":"","value": (res.data.data[i].couponPrice*100),"name":res.data.data[i].couponName,
              "startAt":this.getTimestamp(res.data.data[i].modifiedTime),
              "endAt": this.getTimestamp(res.data.data[i].couponTime),"valueDesc":res.data.data[i].couponPrice,"unitDesc":"元"});
          }else{
            noCoupon.push({ "available": res.data.data[i].couponId,"condition":"满"+res.data.data[i].couponPriceMost +"减"+res.data.data[i].couponPrice
              ,"reason":"","value": (res.data.data[i].couponPrice*100),"name":res.data.data[i].couponName,
              "startAt":this.getTimestamp(res.data.data[i].modifiedTime),
              "endAt": this.getTimestamp(res.data.data[i].couponTime),"valueDesc":res.data.data[i].couponPrice,"unitDesc":"元"});
          }
        }
        // getTimestamp();
      })
      },
      // 进入地址列表
      toAddress(){
        this.$router.push({path:"/my_address"});
      },
      // 门店配送结算订单
      onSubmit1(){
        this.formMaster.invoiceTime = this.orderPaper;
        insertOrderMaster(this.formMaster).then(res=>{
          this.formDetail.orderId = res.data.data;
        let orderId = res.data.data;
        insertOrderDetail(this.formDetail).then(res => {
          if(res.data.code === 200){
          this.$router.push({path:"/AlOneMatePay",
            query:{
              orderId:orderId,
              totalPrice:this.totalPriceb,
              availableId:this.availableId,
              productId:this.productId,
              supplierId:this.supplierIdOnel
            }});
        }
      })
      })
      },
      // 到点自提结算订单
      onSubmit2(){
        this.formMasterB.invoiceTime = this.orderPaper2;
        this.formMasterB.customerPhone = this.phone;
        this.formMasterB.shippingUser = this.username;
        insertOrderMaster(this.formMasterB).then(res=>{
          this.formDetail.orderId = res.data.data;
        let orderId = res.data.data;
        insertOrderDetail(this.formDetail).then(res => {
          if(res.data.code === 200){
          this.$router.push({path:"/AlOneMatePay",query:{orderId:orderId,totalPrice:this.totalPriceb}});
        }
      })
      })
      },
      // 当优惠券内容改变时
      onChange(index) {
        console.log(this.coupons[index]);
        this.showList = false;
        this.chosenCoupon = index;
        if(parseInt(index) != -1){
          this.couponsPrice = this.coupons[index].valueDesc;
          this.availableId = this.coupons[index].available;
        }
        this.getTotalPrice(index);
        this.getTotalPriceb(index);
      },
      onExchange(code) {
        this.coupons.push(coupon);
      },
      // 门店配送总价格
      getTotalPrice(index){
        this.totalPrice = 0;
        if(index == -1){  // 不使用优惠券
          if(this.couponsPrice != null){ // 如果不是空，表示点击过使用优惠券
            this.totalPrice += (this.sku.groupPrice*this.selectedNum);
            this.totalPrice += this.sku.labelFreight;
          }else{ // 如果是空，表示没有点击过使用优惠券
            this.totalPrice += (this.sku.groupPrice*this.selectedNum);
            this.totalPrice += this.sku.labelFreight;
          }
        }else{ // 使用优惠券
          this.totalPrice -= this.couponsPrice;
          this.totalPrice += (this.sku.groupPrice*this.selectedNum);
          this.totalPrice += this.sku.labelFreight;
        }
        this.formMaster.orderMoney = this.totalPrice;
        this.formMaster.districtMoney = this.couponsPrice;
        this.formDetail.feeMoney = this.couponsPrice;
      },
      // 到店自提总价格
      getTotalPriceb(index){
        this.totalPriceb = 0;
        if(index == -1){  // 不使用优惠券
          if(this.couponsPrice != null){ // 如果不是空，表示点击过使用优惠券
            this.totalPriceb += (this.sku.groupPrice*this.selectedNum);
          }else{ // 如果是空，表示没有点击过使用优惠券
            this.totalPriceb += (this.sku.groupPrice*this.selectedNum);
          }
        }else{ // 使用优惠券
          this.totalPriceb -= this.couponsPrice;
          this.totalPriceb += (this.sku.groupPrice*this.selectedNum);
        }
        this.formMasterB.orderMoney = this.totalPriceb;
        this.formMasterB.districtMoney = this.couponsPrice;
      },
      toggle() {
        if(this.orderPaperShow == false){
          this.orderPaperShow = true;
        }else{
          this.orderPaperShow = false;
        }
      },
      toggle2() {
        if(this.orderPaperShow2 == false){
          this.orderPaperShow2 = true;
        }else{
          this.orderPaperShow2 = false;
        }
      },
      // 将时间转换成时间戳
      getTimestamp(time) { //把时间日期转成时间戳
        return (new Date(time)).getTime() / 1000
      },

    },

  }
</script>

<style scoped>
  .demo-nav{
    position: relative;
    display: flex;
    -webkit-box-align: center;
    align-items: center;
    -webkit-box-pack: center;
    justify-content: center;
    height: 45px;
    background-color: #fff;
    font-size: 1.1rem;
  }
  .demo-nav__back{
    position: absolute;
    top: 12px;
    left: 16px;
    width: 24px;
    height: 24px;
    cursor: pointer;
  }
  .OrderDetails-demo{
    padding: 0.5rem;
  }
  .custom-title {
    margin-right: 4px;
    vertical-align: middle;
  }
</style>
